package pacBioSimple;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class ReadAndCorrectRead {

	BufferedReader br = null;
	PrintWriter pw =null;
	HashMap<String, SoapAlignmentObject> alignmentObject=null;
	
	public ReadAndCorrectRead(String InputFile,HashMap<String, SoapAlignmentObject> alignmentObject ,String outputFile) throws Exception
	{
		br = new BufferedReader(new FileReader(InputFile));
		pw = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)));
		this.alignmentObject=alignmentObject;
		// TODO Auto-generated constructor stub
	}
	
	public void readAndCorrect() throws Exception
	{
		while(br.ready())
		{
			String line = br.readLine();
			if(line.startsWith(">"))
			{
				//getHeader
				String name =line.substring(1);
				String seq = br.readLine();
				Fasta fs = new Fasta();
				fs.name=name;
				fs.sequence=seq;
				//check if we have an alignment for that read
				boolean flag=false;
				if(fs.name.indexOf("@m111105_065416_42145_c100180402554500000315046211181160_s1_p0/14")!=-1)
				{
					System.out.println(" auf gehts");
					flag=true;
				}
				else
				{
					flag=false;
				}
				if(alignmentObject.containsKey(name))
				{
					if(flag)
					{
						System.out.println(fs.toString());
					}
					correctRead(fs,flag);

					pw.append(fs.toString());
				}
				else
				{
					//write it back
					pw.append(fs.toString());
				}
			}
		}
	}
	
	//auslagern in tempclass für paralles abarbeiten!
	private void correctRead(Fasta fs,boolean flag)
	{
		SoapAlignmentObject sa = alignmentObject.get(fs.name);
		HashMap<Integer, Character> map = sa.getAlignment();
		//first easy case (only mismatches)
		if(flag)
		{
			System.out.println("seq: "+fs.sequence);
			System.out.println(map.toString());
		}
		char[] seq_rep=fs.sequence.toCharArray();
		for(Map.Entry<Integer, Character> entry : map.entrySet())
		{
			seq_rep[entry.getKey()-1]=entry.getValue();
		}
		if(flag)
		{
			System.out.println(seq_rep);
		}
		fs.sequence=new String(seq_rep);
		if(flag)
		{
			System.out.println(fs.sequence);
		}
	}
	
	
	public class Fasta
	{
		String name="";
		String sequence="";
		
		public String toString()
		{
			StringBuilder sb = new StringBuilder();
			sb.append(">");
			sb.append(this.name+"\n");
			sb.append(this.sequence+"\n");
			return sb.toString();
		}
	}
}
